<template>
	<cl-crud ref="Crud">
		<cl-row>
			<cl-table ref="Table">
				<template #slot-add-btn="{ scope }">
					<!-- <el-button
						:disabled="
							(parentAgentInfo.agentLevelNum == scope.row.agentLevel &&
								scope.row.type == 'node') ||
							(parentAgentInfo.thisUserAgentLevel == 1 && scope.row.type == 'node')
						"
						text
						bg
						type="success"
						@click="append(scope.row)"
						>新增</el-button
					> -->
					<el-button text bg type="success" @click="append(scope.row)">新增</el-button>
				</template>
				<template #slot-edit-btn="{ scope }">
					<el-button
						text
						bg
						type="primary"
						@click="handleEdit(scope.row)"
						v-if="scope.row.type == 'node'"
						>编辑</el-button
					>
				</template>
				<template #slot-del-btn="{ scope }">
					<el-button
						text
						bg
						type="danger"
						@click="handleDelete(scope.row)"
						v-if="scope.row.type == 'node'"
						>删除</el-button
					>
				</template>
			</cl-table>
		</cl-row>
	</cl-crud>

	<!-- 新增代理商弹窗 -->
	<agent-add-view
		v-model:visible="addDialogVisible"
		:parent-id="parentAgentInfo.id"
		:parent-agent-name="parentAgentInfo.name"
		:agent-level="parentAgentInfo.agentLevel"
		:agent-level-num="parentAgentInfo.agentLevelNum"
		:shop-id="parentAgentInfo.shopId"
		@success="handleAddSuccess"
	/>

	<!-- 编辑代理商弹窗 -->
	<agent-edit-view
		v-model:visible="editDialogVisible"
		:parent-agent-name="parentAgentInfo.name"
		:agent-level="parentAgentInfo.agentLevel"
		:agent-level-num="parentAgentInfo.agentLevelNum"
		:shop-id="parentAgentInfo.shopId"
		:agent-user-id="changeAgentUserId"
		:agent-shop-ids="parentAgentInfo.agentShopIds"
		:parent-id="parentAgentInfo.id"
		:agent-id="parentAgentInfo.agentId"
		:agent-obj="agentObj"
		@success="handleEditSuccess"
	/>
</template>

<script lang="ts" setup>
import { useCrud, useTable, useUpsert } from '@cool-vue/crud';
import { service, useCool } from '/@/cool';
import { useStore } from '/$/base/store';
import { reactive, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plugins } from '/#/crud';
import MenuImp from './components/imp.vue';
import MenuExp from './components/exp.vue';
import AgentAddView from '../components/agent-add-view.vue';
import AgentEditView from '../components/agent-edit-view.vue';
import { ElMessage } from 'element-plus';

const { t } = useI18n();

// 控制新增代理商弹窗显示
const addDialogVisible = ref(false);
// 控制编辑代理商弹窗显示
const editDialogVisible = ref(false);
// 选中的代理商ID
const selectedAgentId = ref(0);
// 代理商信息
const parentAgentInfo = reactive({
	id: 0,
	name: '',
	agentLevel: 0,
	agentLevelNum: 0,
	shopId: 0,
	thisUserAgentLevel: 0,
	agentId: 0,
	agentShopIds: []
});

const agentObj = ref({});

const agentRelation = ref([]);

const changeAgentUserId = ref(null);

// 打开新增代理商弹窗
const append = row => {
	parentAgentInfo.name = row.agentName;
	if (row.agentName) {
		parentAgentInfo.id = row.id;
		parentAgentInfo.agentLevel = parseInt(row.agentLevel) + 1;
	} else {
		parentAgentInfo.shopId = row.shop_id;
		parentAgentInfo.agentLevel = row.agentLevel;
	}
	addDialogVisible.value = true;
	console.log(parentAgentInfo);
};

// 处理删除
const handleDelete = row => {
	// service.agnet.agent.deleteAgent({ id: row.id }).then(res => {
	// 	if (res.code === 1) {
	// 		// 删除成功，刷新表格数据
	// 		Crud.value.refresh();
	// 	} else {
	// 		// 删除失败，提示用户
	// 		ElMessage.error(res.msg || '删除失败');
	// 	}
	// });
	service.agent.agent
		.delete({ ids: [row.id] })
		.then(res => {
			// 删除成功，刷新表格数据
			Crud.value.refresh();
		})
		.catch(err => {
			// 删除失败，提示用户
			ElMessage.error('删除失败');
		});
};

// 处理编辑
const handleEdit = row => {
	// 设置选中的代理商ID
	changeAgentUserId.value = row.agentUserId;
	// 设置父代理商信息
	parentAgentInfo.name = row.parentName || '';
	parentAgentInfo.id = row.parentAgentId || 0;
	parentAgentInfo.agentLevel = parseInt(row.agentLevel) || 0;
	parentAgentInfo.shopId = row.shop_id || 0;
	parentAgentInfo.agentId = row.id || 0;
	parentAgentInfo.agentShopIds = row.agentShopIds || [];
	agentObj.value = row;
	console.log('agentObj.value:', agentObj.value);
	// 打开编辑弹窗
	editDialogVisible.value = true;
};

// 处理编辑成功
const handleEditSuccess = () => {
	// 刷新表格数据
	Crud.value.refresh();
};

// 处理新增成功
const handleAddSuccess = () => {
	// 刷新表格数据
	Crud.value.refresh();
};

// 处理后端返回数据（代理商关系）
const handleRefresh = (res) => {
	
};

const Crud = useCrud(
	{
		service: service.agent.agent.queryAgentRelation,
		// service: service.agent.agent.queryAgentRelationV2,
		onRefresh(params, { render }) {
			service.agent.agent.queryAgentRelation().then(res => {
				if (res.length != 0) {
					agentRelation.value = res || [];
					parentAgentInfo.thisUserAgentLevel = res[0].thisUserAgentLevel;
					parentAgentInfo.agentLevelNum = agentRelation.value.length;
				} else {
					res = [
						{
							"id": "root_1",
							"agentType": "一级代理",
							"agentLevel": 1,
							"children": [
							],
							"type": "root",
							"thisUserAgentLevel": 0
						}
					]
				}
				render(res);
			});
			// service.agent.agent.queryAgentRelationV2().then(res => {
			// 	render(res);
			// });
		}
	},
	app => {
		app.refresh({
			// prop: 'orderNum',
			// order: 'asc'
		});
	}
);

// cl-table
const Table = useTable({
	contextMenu: [],
	columns: [
		{
			type: 'selection'
		},
		{
			prop: 'agentType',
			label: t('代理层级'),
			align: 'left',
			width: 200,
			fixed: 'left'
		},
		{
			prop: 'agentShopName',
			label: t('代理商店铺'),
			minWidth: 300
		},
		{
			prop: 'agentName',
			label: t('代理商'),
			minWidth: 300
		},
		{
			prop: 'parentAgentUser',
			label: t('上级代理商'),
			minWidth: 300
		},
		// {
		// 	prop: 'payShop',
		// 	label: t('支付商户'),
		// 	minWidth: 300
		// },
		// {
		// 	prop: 'orderNum',
		// 	label: t('排序号'),
		// 	width: 100,
		// 	fixed: 'right',
		// 	sortable: 'asc'
		// },
		// {
		// 	prop: 'updateTime',
		// 	label: t('更新时间'),
		// 	sortable: 'custom',
		// 	width: 170
		// }
		{
			type: 'op',
			width: 250,
			buttons: ['slot-add-btn', 'slot-edit-btn', 'slot-del-btn']
		}
	],
	// 表格属性配置
	props: {
		// 自定义row-key字段
		'row-key': 'parentAgentId' // 将'你的自定义字段名'替换为实际需要的字段名
	},
	plugins: [
		Plugins.Table.toTree({
			lazy: true
		})
	]
});

const Upsert = useUpsert({
	dialog: {
		width: '800px'
	},
	items: [
		{
			prop: 'name',
			label: t('节点名称'),
			component: {
				name: 'el-input'
			},
			required: true
		}
	]
	// plugins: [Plugins.Form.setFocus('name')]
});

defineOptions({
	name: 'agent-shop'
});
</script>
